<script lang="ts" setup>
import type { Ref } from 'vue'
import { onBeforeUnmount, onDeactivated, ref, unref } from 'vue'
import type VditorPreview from 'vditor/dist/method.min'

const viewerRef = ref<ElRef>(null)
const vditorPreviewRef = ref(null) as Ref<Nullable<VditorPreview>>

function destroy() {
  const vditorInstance = unref(vditorPreviewRef)
  if (!vditorInstance)
    return
  try {
    vditorInstance?.destroy?.()
  }
  catch (error) {}
  vditorPreviewRef.value = null
}

onBeforeUnmount(destroy)
onDeactivated(destroy)
</script>

<template>
  <div id="markdownViewer" ref="viewerRef" :class="$props.class" />
</template>
